import { defineStore } from "pinia"
import { ref } from "vue"
import { computed } from "vue"
import { useUserStore } from "./user"
import { insertCartAPI, getCartListAPI } from "@/apis/cart"

export const useCartStore = defineStore("cart", () => {
  const cartList = ref([])
  const userStore = useUserStore()
  const isLogin = computed(() => userStore.userInfo.token)

  const updateNewList = async () => {
    const res = await getCartListAPI()
    cartList.value = res.result
  }
  const addCart = async (goods) => {
    const { skuId, count } = goods
    if (isLogin.value) {
      //登陆后的加入购物车
      await insertCartAPI({ skuId, count })
      updateNewList()
    } else {
      const findResult = cartList.value.find((item) => item.skuId === goods.skuId)
      if (findResult) {
        findResult.count += goods.count
      } else {
        cartList.value.push(goods)
      }
    }
  }

  const delCart = (id) => {
    //1、使用splice方法，删除数组中的元素
    /* const idx = cartList.value.findIndex((item) => id === item.skuId)
    cartList.value.splice(idx, 1) */
    //2、使用filter方法，删除数组中的元素
    cartList.value = cartList.value.filter(item => item.skuId !== id)
  }

  const clearCart = () => {
    cartList.value = []
  }
  //单选功能
  const singleCheck = (skuId, selected) => {
    const item = cartList.value.find(i => i.skuId === skuId)
    item.selected = selected
  }
  //全选功能
  const allCheck = selected => {
    cartList.value.forEach(el => el.selected = selected
    )
  }
  //计算属性
  //1、总的数量
  const totalCount = computed(() => {
    return cartList.value.reduce((preValue, item) => {
      return preValue + item.count
    }, 0)
  })

  const selectedCount = computed(() => cartList.value.filter(i => i.selected).reduce((preValue, item) => preValue + item.count, 0))
  //2、总的金额
  const totalPrice = computed(() => {
    return cartList.value.reduce((preValue, item) => {
      return preValue + item.count * item.price
    }, 0)
  })

  const selectedPrice = computed(() => cartList.value.filter(i => i.selected).reduce((preValue, item) => preValue + item.count * item.price, 0))
  //是否全选isAll
  const isAll = computed(() => cartList.value.every(i => i.selected))
  return {
    cartList, addCart, delCart, clearCart, totalCount, totalPrice, singleCheck, isAll, allCheck, selectedCount, selectedPrice, updateNewList
  }
}, {
  persist: true
})